/**
 * Returns true if the score should be cleared
 */
boolean initLevel()
{
  int level = userLevel[difficulty];
  println(level);
 
  compSystem = new SolarSystem(difficulty);
  compSystem.genSystem();
  print("System Formula : " + compSystem.fullFormula + "\n");
  
  //load the right level outline for difficulty and level
  String outlineFilename = getOutlineFilename();
  print(outlineFilename);
  levelOutline = loadImage(outlineFilename);
  if (levelOutline == null)
  {
    userLevel[difficulty] = 1;
    initLevel();
    return true;
  }
  // todo: load the appropriate leve for the given level and difficulty
  
  globalShapeContainer.initStandardShapes();
  
  // todo: generate solar system
  
  if (compSystem != null && compSystem.fullFormula != null)
  {
    globalClueOverlay.generateNewClues(compSystem.fullFormula, "assign");
  }
  
  return false;
}

/**
 * The outline file contains the outline that the user is supposed to match their shapes up to
 * Determined by difficulty and level
 */
String getOutlineFilename()
{
  String outlineFilename = "levels/";
  if(difficulty == 0)
    outlineFilename += "easy";
  if(difficulty == 1)
    outlineFilename += "med";
  if(difficulty == 2)
    outlineFilename += "hard";
  outlineFilename += userLevel[difficulty];
  outlineFilename += ".png";
  return outlineFilename;
}

void levelsSetup()
{
  loadUserLevels();
}

void loadUserLevels()
{
  String lns[] = loadStrings("levels/userLevels.txt");
  
  if (lns == null || lns.length < 3)
  {
    return;
  }
  
  userLevel[0] = int(lns[0]);
  userLevel[1] = int(lns[1]);
  userLevel[2] = int(lns[2]);
}

void saveUserLevels()
{
  String strs[] = new String[userLevel.length];
  
  for (int i = 0; i < strs.length; i++)
  {
    strs[i] = "" + userLevel[i];
  }
  
  saveStrings("levels/userLevels.txt", strs);
}

void loadNextLevel()
{
  println("CORRECT SOLUTION!");
  String IDs = globalShapeContainer.getElementIDs(false);
  print(IDs + "\n");
  userSystem.buildSystem(IDs);
  setGameState(3);
  
  if (userSystem != null && compSystem != null)
  {
    score(userSystem.fullFormula, compSystem.fullFormula);
  }
  saveScores();
  if(levelScores[difficulty] >= minScore + difficulty)
  {  
    userLevel[difficulty]++;
  }
  saveUserLevels();
  
  // if the next file doesn't exist, then there isn't a next level
  // go back to the menu screen
  if (loadImage(getOutlineFilename()) == null)
  {
    globalScoreScreen.reset();
    globalScoreScreen.setNextGameState(1);
    globalScoreScreen.clearScores = true;
    return;
  }
  
  if (levelScores[difficulty] < minScore+difficulty)
  {
    totalScores[difficulty] -= levelScores[difficulty];
    saveScores();
    globalScoreScreen.setNextGameState(1);
    return;
  }
  
  globalScoreScreen.setNextGameState(2);
  initLevel();
}
